<template>
  <el-dialog
    v-model="dialogVisible"
    title="发表评价"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="comment-content">
      <!-- 商品信息 -->
      <div class="goods-info">
        <img :src="getImageUrl(order?.picture)" class="goods-image" />
        <div class="goods-detail">
          <h4 class="goods-name">{{ order?.goodsName }}</h4>
        </div>
      </div>

      <!-- 评价表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="评分" prop="rating">
          <el-rate 
            v-model="form.rating" 
            :texts="['极差', '失望', '一般', '满意', '惊喜']"
            show-text
          />
        </el-form-item>

        <el-form-item label="评价内容" prop="comment">
          <el-input
            v-model="form.comment"
            type="textarea"
            :rows="5"
            placeholder="说说你的使用感受吧~"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="评价图片">
          <ImageUpload
            v-model="form.image"
            prefix="comment"
            :max-size="5"
          />
          <div class="upload-tip">上传图片可以让评价更有说服力（选填）</div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          :loading="submitting"
          @click="handleSubmit"
        >
          提交评价
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { addComment } from '@/api/comment'
import { getFileUrl } from '@/api/file'
import { ElMessage } from 'element-plus'
import ImageUpload from './ImageUpload.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  order: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(props.modelValue)
const formRef = ref(null)
const submitting = ref(false)

const form = reactive({
  rating: 5,
  comment: '',
  image: ''
})

const rules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  comment: [
    { required: true, message: '请填写评价内容', trigger: 'blur' },
    { min: 10, message: '评价内容至少10个字', trigger: 'blur' }
  ]
}

// 监听外部传入的值
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    resetForm()
  }
})

// 监听内部值变化，同步到外部
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 提交评价
const handleSubmit = async () => {
  if (!formRef.value || !props.order) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await addComment({
          orderId: props.order.id,
          goodsId: props.order.goodsId,
          rating: form.rating,
          comment: form.comment,
          image: form.image || undefined
        })

        ElMessage.success('评价成功')
        dialogVisible.value = false
        emit('success')
        resetForm()
      } catch (error) {
        console.error('评价失败:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.rating = 5
  form.comment = ''
  form.image = ''
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getFileUrl(imagePath)
}
</script>

<style scoped>
.comment-content {
  padding: 10px 0;
}

.goods-info {
  display: flex;
  gap: 15px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 20px;
}

.goods-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.goods-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.goods-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-rate) {
  height: 32px;
}

:deep(.el-rate__text) {
  font-size: 14px;
  color: #666;
}
</style>
